package com.agent.service.impl;

import com.agent.entity.Dept;
import com.agent.entity.User;
import com.agent.service.IDeptService;
import com.agent.service.UserService;
import com.agent.util.Constants;
import com.agent.util.Md5Utils;
import com.weixin.util.WXUtil;
import com.weixin.util.WxepConstants;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by hg on 2019/1/8.
 */
@Service("scheduleUser")
public class ScheduleUser {


    @Resource(name = "userServiceImpl")
    UserService userService;

    @Resource(name = "deptServiceImpl")
    IDeptService deptService;

    public void execute(){
//        userService.deleteByCreator();
        Dept dept = new Dept();
        dept.setOwnerSystem(Constants.SYSTEM);
        List<Dept> depts = deptService.listNoPage(dept);
        depts.forEach(dept1 -> {
            if(!StringUtils.isEmpty(dept1.getQywxId())){
                sycUser(WxepConstants.REPAIRE_SECRET,dept1.getQywxId());   //客户部门
            }
        });



    }


    public void sycUser(String secret,String deptId){
        String accessToken = WXUtil.getToken(WxepConstants.CorpId,secret);
        String url = WxepConstants.GET_USERLIST_URL.replace("{accessToken}",accessToken)
                .replace("{deptId}",deptId).replace("{fetchChild}","0");
        JSONObject result = WXUtil.httpRequest(url, "GET", null);
        if(WxepConstants.SUCCESS_CODE ==result.getInt("errcode")){
            JSONArray jsonArray = result.getJSONArray("userlist");
            List<Map<String,Object>> userLists = (List)jsonArray;
            if(userLists.size()>0){
                userService.saveOrUpdate(assemblyUserInfo(userLists));
            }
        }
    }


    private List<User>  assemblyUserInfo(List<Map<String,Object>> userLists){
        List<User> resultUser = new ArrayList<>();
        userLists.forEach(entry -> {
            User user = new User();
            user.setCreateTime(new Date());
            user.setCreator(Constants.SYSTEM);
            if(!StringUtils.isEmpty(String.valueOf(entry.get("department")))){
                // 将[] 去除
                user.setDeptId(String.valueOf(entry.get("department")).replace("[","").replace("]",""));
            }
            user.setDisplayName(String.valueOf(entry.get("name")));
            user.setTelphone(String.valueOf(entry.get("mobile")));
            user.setPassword(Md5Utils.encryptPassword(Constants.INIT_PASSWORD));
            user.setRoleId(5);
            user.setEmail(String.valueOf(entry.get("email")));
            user.setUserName(String.valueOf(entry.get("userid")));
            user.setEnabled("1".equals(String.valueOf(entry.get("status"))));
            String gender = String.valueOf(entry.get("gender"));// 0表示未定义，1表示男性，2表示女性
            user.setSex(String.valueOf(entry.get("gender")));
            resultUser.add(user);
        });
        return resultUser;
    }
}
